<template>
<div class="add-box">
  <h2>填写报告</h2>
  <form @submit.prevent="submit">
    <fieldset v-for="(o, i) of format">
      <legend>{{o.legend}}</legend>
      <input 
        v-if="!o.textarea"
        :maxlength="o.maxlength"
        :required="o.required"
        v-model.trim="models[i]"
        type="text">
      <textarea
        v-if="o.textarea"
        :maxlength="o.maxlength"
        :required="o.required"
        v-model.trim="models[i]"
        ></textarea>
    </fieldset>
    <input type="submit" value="提交">
  </form>
  <div class="mask" v-if="maskShown">
    <div @click="again">再写一份</div>
  </div>
</div>
</template>

<script>
import ajaks from 'ajaks';
import format from './format';

const emptyModels = Array(format.length).fill('');

export default {
  data () {
    return {
      format,
      models : emptyModels.slice(),
      maskShown : false,
      submitable : true,
    };
  },
  methods : {
    submit (e) {
      if (!this.submitable) return;
      this.submitable = false;
      ajaks.post('/api/add', {
        content : this.getContent(),
      }).then(data => {
        if (data.code === 0) {
          this.maskShown = true;
        } else {
          console.log(data.err);
        }
        this.submitable = true;
      }).catch(e => {
        this.submitable = true;
      });
    },
    getContent () {
      const arr = this.models.map((value, i) => ({
        text : this.format[i].legend,
        value,
      }));
      return JSON.stringify(arr);
    },
    again () {
      this.models = emptyModels.slice();
      this.maskShown = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.add-box {
  position:relative;
  width:100%; height:100%;
  overflow-x:hidden; overflow-y:scroll;
}
input[type="submit"] {
  width:10rem; height:3.5rem;
  margin:0 auto 2rem;
  background:rgb(3,169,244); color:white;
}
.mask {
  position:absolute;
  left:0; top:0;
  width:100%; height:100%;
  background:white;
  & > div {
    position:absolute;
    left:0; right:0;
    width:10rem; height:3rem;
    border-radius:3px; margin:auto;
    background:rgb(3,169,244); color:white;
    text-align:center; line-height:3rem;
  }
  & > div:nth-child(1) {top:5rem;}
  & > div:nth-child(2) {top:9rem; background:red;}
}
</style>
